<?php
/**
 * 结算相关
 */

namespace app\api\controller\task;


use app\common\controller\AppCommon;
use app\service\MerchantCredits;
use think\Db;

class Settlement extends TaskBase
{
    //商家订单结算
    public function order_merchant()
    {
        if (!bs_p('merchant')) {
            data_return('未安装启用多商户功能，不支持结算', -1);
        }
        $stime = strtotime("-7 days");
        $where = ['o.is_settlement' => 0, 'o.is_parent' => 0, 'o.status' => ['>', 3], 'o.receive_time' => ['<=', $stime]];

        $data = AppCommon::db('order')
            ->alias('o')
            ->join('stores s', 'o.store_num=s.store_num', 'left')
            ->where($where)
            ->field('o.id,o.order_sn,o.uid,o.status,o.price,o.pay_price,o.pay_time,o.pay_type,o.store_num,o.refund_total,o.order_type,s.store_name,s.merchant_uid')
            ->order('o.receive_time asc')
            ->limit(20)
            ->select();
        if (empty($data)) {
            data_return('暂无需要结算的订单，查询截止时间：' . date('Y-m-d H:i:s', $stime), -1);
        }
        foreach ($data as $item) {
            //需要结算金额
            $num = $item['pay_price'] - $item['refund_total'];
            if ($num <= 0) {
                //直接更新为已结算
                \app\service\Order::update($item['order_sn'], ['is_settlement' => 1]);
                continue;
            } else {
                Db::startTrans();
                $res = \app\service\Order::update($item['order_sn'], ['is_settlement' => 1]);
                if (!$res) {
                    Db::rollback();
                    continue;
                }
                //到账货款
                $u = MerchantCredits::update($item['merchant_uid'], 'credit', $num, [
                    'remark' => $item['order_sn'] . '订单货款结算',
                    'type' => 1
                ]);
                if (!$u) {
                    Db::rollback();
                    continue;
                }
                Db::commit();
            }
        }

        data_return('ok', 0, $data);
    }
}